import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr



# 发件人邮箱和授权码（不是邮箱登录密码）
sender_email = 'kang_fengjian@163.com'  # 替换为你的QQ邮箱
sender_code = 'ZCmqDxHBcH8h6Qm5'  # 替换为你的QQ邮箱授权码

# 收件人邮箱
receiver_email = 'kangfengjian@qq.com'  # 替换为收件人邮箱

# 构建邮件内容
msg = MIMEText('这是一封来自 Python 的测试邮件。', 'plain', 'utf-8')  # 纯文本正文
msg['From'] = formataddr(('发件人昵称', sender_email))  # 发件人信息
msg['To'] = formataddr(('收件人昵称', receiver_email))  # 收件人信息
msg['Subject'] = 'Python邮件测试'  # 邮件主题

try:
    # 连接163邮箱的SMTP服务器（SSL加密）
    server = smtplib.SMTP_SSL('smtp.163.com', 465)
    # 登录邮箱
    server.login(sender_email, sender_code)
    # 发送邮件
    server.sendmail(sender_email, [receiver_email], msg.as_string())
    print('邮件发送成功！')
except Exception as e:
    print(f'邮件发送失败: {e}')
finally:
    # 关闭连接
    server.quit()